const createError = require('http-errors');
const express = require('express');
const path = require('path');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const http = require('http');
const { Server } = require("socket.io");

const app = express();
const server = http.createServer(app);

// 实例化 io 对象
const io = new Server(server);

const authControll = require('./utils/authControll');

const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(session({
  secret: 'ncalsnclanklinlnkxjsnkjx',
  name: 'myadmin',
  cookie: {
    maxAge: 1000 * 60 * 60
  },
  resave: false,
  saveUninitialized: true,
  rolling: true
}));

// 路由拦截
app.use(authControll);

app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  console.log('服务器500：', err);
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// module.exports = app;

const users = {}; // 保存所有上线用户信息

// io 处理
// 建立连接
io.on('connection', (socket) => {
  // socket 表示当前连接用户对象
  // socket.id 是每一个连接的 id
  console.log('接收到一个客户端的连接：', socket.id);

  // 检测用户上线事件
  // online 事件是自定义事件
  // info 是触发该事件时，传递的 参数
  socket.on('online', info => {
    users[socket.id] = info;
    console.log('当前上线后所有用户信息：', users);

    // 向客户端所有用户广播在线列表
    io.emit('client-online', users);
  });

  // 接受客户端发送的消息
  socket.on('message', data => {
    console.log('接收到客户端发送的聊天消息：', data);

    if (data.toWho) {
      let id = findId(data.username);
      // 私聊, to(socket.id)
      console.log('私聊id：', id)
      io.to(id).emit('client-message', data)
    } else {
      // 将消息广播给所有用户
      io.emit('client-message', data);
    }
  });

  // 下线
  socket.on("disconnect", (reason) => {
    console.log('用户下线：', reason, socket.id);

    for (let key in users) {
      if (key == socket.id) {
        delete key;
      }
    }

    io.emit('client-online', users);
  });
});

server.listen(3000, () => {
  console.log('server is running at port 3000');
});

function findId(username) {
  for (var key in users) {
    if (users[key].username == username) {
      return key;
    }
  }
}